//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	SqlQueryBuilderStatementItem.cs
//  Developer:	Solomatov Igor
//  Created:	15.04.2012
// 
//  -------------------- iSharePoint -------------------- //

namespace Smart.Common.Entities
{
	/// <summary>
	/// QueryBuilder Query Statement Item
	/// </summary>
	public class SqlQueryBuilderStatementItem<TExecutorType> : SqlQueryBuilderItem<TExecutorType>
		where TExecutorType : class
	{
		/// <summary>
		/// Field
		/// </summary>
		public string Field { get; set; }

		/// <summary>
		/// Field
		/// </summary>
		public string FieldOptions { get; set; }

		/// <summary>
		/// Statement
		/// </summary>
		public string Statement { get; set; }

		/// <summary>
		/// QueryBuilder Query Condition Item
		/// </summary>
		/// <param name="field">Field name</param>
		/// <param name="fieldOptions">Field options</param>
		/// <param name="op">Operation</param>
		/// <param name="statement">Statement</param>
		public SqlQueryBuilderStatementItem(string field, string fieldOptions, string op, string statement)
			: base(op)
		{
			Field = field;
			FieldOptions = fieldOptions;
			Statement = statement;
		}

		/// <summary>
		/// Return Cache code
		/// </summary>
		public override int GetCacheCode()
		{
			return
				(Field == null ? 0 : Field.GetHashCode()) ^
				(FieldOptions == null ? 0 : FieldOptions.GetHashCode()) ^
				(Statement == null ? 0 : Statement.GetHashCode()) ^
				(Op == null ? 0 : Op.GetHashCode());
		}

		/// <summary>
		/// Format QueryBuilder statement
		/// </summary>
		public override string FormatQuery()
		{
			return
				Field.IsNullOrEmpty()
					? Statement
					: string.Format("{0}{1}{2}{3}",
									(Query == null ? Field : Query.Meta.FieldName(Field)),
									(FieldOptions.IsNullOrEmpty() ? string.Empty : " " + FieldOptions.TrimStart()),
									(Op.IsNullOrEmpty() ? string.Empty : " " + Op.TrimStart()),
									(Statement.IsNullOrEmpty() ? string.Empty : " " + Statement.TrimStart()));
		}
	}
}